export const compressImg = (file) => {
  return new Promise((resolve, reject) => {
    const image = new Image()
    image.src = URL.createObjectURL(file)
    image.onload = () => {
      let resultBlob = compressUpload(image, file)
      const fs = new File([resultBlob], file.name, {
        type: file.type
      })
      resolve(fs)
    }
    image.onerror = () => {
      reject()
    }
  })
}

const compressUpload = (image, file) => {
  const percent: number =
    1000 / (file.size / 1024) >= 1
      ? 1
      : 1000 / Number((file.size / 1024).toFixed(2))
  const canvas = document.createElement('canvas')
  const ctx = canvas.getContext('2d')
  const { width, height } = image
  canvas.width = width
  canvas.height = height
  ctx?.fillRect(0, 0, canvas.width, canvas.height)
  ctx?.drawImage(image, 0, 0, width, height)
  const comressData = canvas.toDataURL(
    file.type || 'image/jpeg',
    percent
  )
  const blobImg = dataURIToBlob(comressData)
  return blobImg
}

const dataURIToBlob = (data) => {
  let byteString
  if (data.split(',')[0].indexOf('base64') > -1) {
    byteString = atob(data.split(',')[1])
  } else {
    byteString = unescape(data.split(',')[1])
  }
  const mimeString = data
    .split(',')[0]
    .split(':')[1]
    .split(':')[0]
  const ia = new Uint8Array(byteString.length)
  for (let i = 0; i < byteString.length; i += 1) {
    ia[i] = byteString.charCodeAt(i)
  }
  return new Blob([ia], { type: mimeString })
}

export const getDaysInMonth = (year, month) => {
  return new Date(year, month, 0).getDate()
}

export const isEmpty = (value) => {
  return ![null, undefined].includes(value)
}

export const isHasData = (value) => {
  return [null, undefined, {}, []].includes(value)
}

export const dateArrayJoin = (list: any[]) => {
  const arr: any[] = []
  list.forEach((e) => {
    if (e.toString().length > 1) {
      arr.push(e)
    } else {
      arr.push(`0${e}`)
    }
  })
  return arr.join('-')
}

export const initMonthTimeRange = () => {
  const year = new Date().getFullYear()
  const month =
    (new Date().getMonth() + 1).toString().length > 1
      ? new Date().getMonth() + 1
      : `0${new Date().getMonth() + 1}`
  const day =
    getDaysInMonth(year, month).toString().length > 1
      ? getDaysInMonth(year, month).toString()
      : `0${getDaysInMonth(year, month)}`
  const startDate = `${year}-${month}-01`
  const endDate = `${year}-${month}-${day}`
  return [startDate, endDate]
}

export const getDisabledStatus = (date) => {
  return (
    date.getTime() >= Date.now() - getCurrentTimeStamp()
  )
}

export const getCurrentTimeStamp = () => {
  return (
    (new Date().getHours() * 3600 +
      new Date().getMinutes() * 60 +
      new Date().getSeconds()) *
      1000 +
    new Date().getMilliseconds()
  )
}
